package com.bankLogisticsSys.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bankLogisticsSys.model.Userinfo;
import com.bankLogisticsSys.service.ManageUserService;
import com.bankLogisticsSys.service.TransformService;
import com.bankLogisticsSys.util.Sha1;
import com.bankLogisticsSys.util.WeixinUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

/** 
* @author 作者 :		xueyu 
* @date 创建时间:		2017年6月19日 下午5:14:26
* @version 版本:				 
* @description:		
*/

public class LoginController extends BaseController {
	private String signature;
	private String timestamp;
	private String nonce;
	private String echostr;
	public ManageUserService uservice = new ManageUserService();
	
	private static final Logger logger = LoggerFactory
			.getLogger(LoginController.class);
	public void index() throws IOException {
		if(OAUTH2_OPEN){
		String code   = getPara("code");
		if (StrKit.isBlank(code)) {
			renderText("code is Blank!");
		}
		openId = OauthOpenId(code);
		}
		Record user1 = exservice.getUserinfoCN(openId);
		if(user1 != null){
			setAttr("msg","您已经绑定帐号，再次登陆将重新绑定");
			setAttr("userinfo", user1);
			render("/WEB-INF/content/userinfo.html");
		}else{
			render("/WEB-INF/content/login.html");
		}
	}
	public void relogin(){
		render("/WEB-INF/content/login.html");
	}
	
	// login verify
	public void login() {
		if(OAUTH2_OPEN){
		String code   = getPara("code");
		if (StrKit.isBlank(code)) {
			renderText("code is Blank!");
		}
		openId = OauthOpenId(code);
		}
		ApiConfigKit.setThreadLocalApiConfig(WeixinUtil.getApiConfig());
		String employeeID = getPara("employeeID");
		String password = getPara("password");
		System.out.println("this is openId: login " + openId);
		Userinfo user = uservice.getUserByNameAndPass(employeeID, password);
		Userinfo user1 = uservice.getUserByOpenid(openId);
		int oldTag = 2;
		if(user!=null){
			if(user1 != null){
				oldTag = TransformService.getTagByRole(user1.getRole());
				user1.setOpenID(null);
				user1.update();
			}
			user.setOpenID(openId);
			user.update();
			logger.info(getLogString(openId, "登录", new HashSet<String>()));
			/*
			 * 为账号添加标签，便于访问个性化菜单
			 * 100:银行网点
			 * 101:银行分行
			 * 102:邮政网点
			 * 103:分拨中心
			 * 104:揽投员
			 */
			switch(user.getRole()){
			case 0: break;
			case 1: System.out.println(TagApiController.userBatchUpdate(openId, 100));break;
			case 2: System.out.println(TagApiController.userBatchUpdate(openId, 101));break;
			case 3: TagApiController.userBatchUpdate(openId, 102);break;
			case 4: TagApiController.userBatchUpdate(openId, 103);break;
			case 5: TagApiController.userBatchUpdate(openId, 104);break;
			case 6: break;
			case 7: break;
			default:logger.info("wooooooooooooooooow!");
			}
			setAttr("userinfo",exservice.getUserinfoCN(openId));
			render("/WEB-INF/content/userinfo.html");
		}else{
			setAttr("msg","用户名或密码错误，请重新输入");
			render("/WEB-INF/content/login.html");
		}
	}
	
	
	public void modifyPass(){
		render("/WEB-INF/content/modifyPassword.html");
	}
	
	public void modifyPassword(){
		if(OAUTH2_OPEN){
		String code   = getPara("code");
		if (StrKit.isBlank(code)) {
			renderText("code is Blank!");
		}
		openId = OauthOpenId(code);
		}
		String newPassword = getPara("newPassword");
		String oldPassword = getPara("oldPassword");
		Userinfo user = exservice.getUserinfo(openId);
		System.out.println(user);
		System.out.println(oldPassword);
		if(user!=null && user.getPassword().equals(oldPassword)){
			user.setPassword(newPassword);
			user.update();
			render("/WEB-INF/content/login.html");
		}else{
			setAttr("errMsg","原密码错误，请重新输入");
			render("/WEB-INF/content/modifyPassword.html");
		}
	}
	
	public void access(){
		  
		ArrayList<String> list=new ArrayList<String>();
		list.add( getPara("nonce"));
		list.add( getPara("timestamp"));
		list.add("whfenghuokaizhuoa1s23f4g5");

		Collections.sort(list);
		//这种打印出的字符串顺序和微信官网提供的字典序顺序是一致的  
		String data = "";
		for(int i=0, size=list.size();i<size;i++){  
		data += list.get(i);
		}  
		System.err.println(getPara("signature"));
		System.err.println(getPara("timestamp"));
		System.err.println(getPara("nonce"));
		System.err.println(getPara("echostr"));
		System.out.println("hex_sha1(" + data + ")=" + Sha1.hex_sha1(data));
		if(getPara("signature").equals(Sha1.hex_sha1(data))){
			renderText(getPara("echostr"));
		}
	}
	
	public static String getSha1(String str){
	    if (null == str || 0 == str.length()){
	        return null;
	    }
	    char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
	            'a', 'b', 'c', 'd', 'e', 'f'};
	    try {
	        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
	        mdTemp.update(str.getBytes("UTF-8"));
	         
	        byte[] md = mdTemp.digest();
	        int j = md.length;
	        char[] buf = new char[j * 2];
	        int k = 0;
	        for (int i = 0; i < j; i++) {
	            byte byte0 = md[i];
	            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
	            buf[k++] = hexDigits[byte0 & 0xf];
	        }
	        return new String(buf);
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	     // TODO: handle exception
	    }
	    return null;
	}
	public void logout(){
		removeSessionAttr("userinfo");
		redirect("/");
	}

	public String getSignature() {
		return signature;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getNonce() {
		return nonce;
	}

	public void setNonce(String nonce) {
		this.nonce = nonce;
	}

	public String getEchostr() {
		return echostr;
	}

	public void setEchostr(String echostr) {
		this.echostr = echostr;
	}

}
